package com.demo.tomcat;


import com.demo.rule.servlet.MyServlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class MyTomcat {


    private int port = 8090;
    private ServerSocket serverSocket;

    private Map<String, MyServlet> map = new HashMap<>();

    private Properties xmlWeb = new Properties();


    public static void main(String[] args) {
        new MyTomcat().start();
    }

    private void init() {
        try {
            String web_inf = this.getClass().getResource("/").getPath();
            FileInputStream inputStream = new FileInputStream(web_inf + "web.properties");
            xmlWeb.load(inputStream);
            //
            for (Object k : xmlWeb.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String servletName = key.replaceAll("\\.url", "");
                    String url = xmlWeb.getProperty(key);
                    String className = xmlWeb.getProperty(servletName + ".className");
                    //单实例 多线程
                    Class<?> aClass = this.getClass().getClassLoader().loadClass(className);
                    MyServlet servlet = (MyServlet) aClass.newInstance();
                    map.put(url, servlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        //加载配置文件
        init();
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("启动服务监听端口：8090");
            while (true) {
                Socket socket = serverSocket.accept();
                process(socket);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket socket) throws Exception {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        //封装
        MyRequest myRequest = new MyRequest(inputStream);
        MyResponse myResponse = new MyResponse(outputStream);
        String url = myRequest.getUrl();
        if (map.containsKey(url)) {
            MyServlet servlet = map.get(url);
            servlet.service(myRequest, myResponse);
        }else {
            outputStream.write("404 - Not Found".getBytes(StandardCharsets.UTF_8));
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
        socket.close();
    }
}
